import 'package:auto_route/auto_route.dart';
import 'package:casdon/app/config/theme/theme_extention.dart';
import 'package:casdon/build_gen/assets.gen.dart';
import 'package:casdon/common/widget/common_loading_widget.dart';

import 'package:casdon/modules/recipe/application/notification/course_tags_provider.dart';
import 'package:casdon/modules/recipe/ui/screen/course_list_screen.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

@RoutePage()
class CookCourseScreen extends ConsumerStatefulWidget {
  final String moduleId;

  const CookCourseScreen({super.key, required this.moduleId});

  @override
  ConsumerState<CookCourseScreen> createState() => _CookCourseState();
}

class _CookCourseState extends ConsumerState<CookCourseScreen>
    with TickerProviderStateMixin {
  TabController? _tabController;
  final PageController _pageController = PageController();

  @override
  Widget build(BuildContext context) {
    final tagsAsync = ref.watch(courseTagsProvider);

    return Scaffold(
      backgroundColor: Colors.white,
      body: tagsAsync.when(
        data: (tags) {
          _tabController ??= TabController(length: tags.length, vsync: this);

          return NestedScrollView(
            headerSliverBuilder: (context, innerBoxIsScrolled) => [
              SliverAppBar(
                automaticallyImplyLeading: true,
                backgroundColor: Colors.transparent,
                elevation: 0,
                expandedHeight: 124.h, // 头图高度
                pinned: true,
                flexibleSpace: FlexibleSpaceBar(
                  background: Stack(
                    fit: StackFit.expand,
                    children: [
                      Image.asset(
                        Assets.images.cookHeader.path,
                        fit: BoxFit.cover,
                      ),
                    ],
                  ),
                ),
              ),
              SliverToBoxAdapter(child: SizedBox(height: 18.h)),

              SliverPersistentHeader(
                pinned: true,
                delegate: _SliverTabBarDelegate(
                  Container(
                    alignment: Alignment.centerLeft,
                    padding: const EdgeInsets.only(left: 8),
                    child: Transform.translate(
                      offset: const Offset(-48, 0),
                      child: TabBar(
                        controller: _tabController,
                        isScrollable: true,
                        indicatorColor: context.colorScheme.primary,
                        indicatorWeight: 3,
                        indicatorPadding: const EdgeInsets.symmetric(
                          horizontal: 8,
                        ),
                        labelColor: context.colorScheme.primary,
                        unselectedLabelColor:
                            context.customColorThemeNonNull.textColor1,
                        labelStyle: context.textTheme.bodyLarge!.copyWith(
                          color: context.colorScheme.primary,
                        ),
                        unselectedLabelStyle: context.textTheme.bodyMedium!
                            .copyWith(
                              color: context.customColorThemeNonNull.textColor1,
                            ),
                        labelPadding: EdgeInsets.symmetric(horizontal: 16.w),
                        dividerColor: context.colorScheme.surface,
                        tabs: tags.map((e) => Tab(text: e.name)).toList(),
                        onTap: (index) => _pageController.jumpToPage(index),
                      ),
                    ),
                  ),
                ),
              ),
            ],
            body: PageView.builder(
              controller: _pageController,
              itemCount: tags.length,
              onPageChanged: (index) {
                _tabController!.animateTo(index);
              },
              itemBuilder: (_, index) {
                final tag = tags[index];
                return CourseListScreen(
                  moduleId: widget.moduleId,
                  tagId: tag.id,
                );
              },
            ),
          );
        },
        loading: () => const Center(child: CommonLoadingWidget()),
        error: (e, _) => Center(child: Text('加载失败')),
      ),
    );
  }
}

class _SliverTabBarDelegate extends SliverPersistentHeaderDelegate {
  final Widget _tabBar;

  _SliverTabBarDelegate(this._tabBar);

  @override
  double get minExtent => 48.h;
  @override
  double get maxExtent => 48.h;

  @override
  Widget build(
    BuildContext context,
    double shrinkOffset,
    bool overlapsContent,
  ) {
    return Container(
      color: Colors.white,
      child: Theme(
        data: Theme.of(context).copyWith(
          dividerColor: Colors.transparent,
          splashColor: Colors.transparent,
          highlightColor: Colors.transparent,
        ),
        child: Material(color: Colors.white, elevation: 0, child: _tabBar),
      ),
    );
  }

  @override
  bool shouldRebuild(_SliverTabBarDelegate oldDelegate) => false;
}
